function reloadServerList() {
  fetch('/getServerList')
    .then(function(res) {
      return res.json();
    })
    .then(function(json) {
      console.log(json);
      //   store.servers.push({ name: "android", version: "3.0.1" });
      store.servers = json;
    })
    .catch(e => {
      // alert('getAppList fail:' + e);
      throw e;
    });
}

async function setDockerRegistry(value) {
  console.log('add server', name);
  let res = await fetch('/setDockerRegistry', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ value }),
  });
  let err = res.ok ? (await res.json()).err : null;
  return [res.ok, err];
}

async function addServer(name, ip) {
  console.log('add server', name);
  let res = await fetch('/addServer', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ip, name }),
  });
  let err = res.ok ? (await res.json()).err : null;
  return [res.ok, err];
}

async function updateServer(name) {
  console.log('update server', name);
  let res = await fetch('/updateServer', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name }),
  });
  let err = res.ok ? (await res.json()).err : null;
  return [res.ok, err];
}

async function removeServer(name) {
  console.log('remove server', name);
  let res = await fetch('/removeServer', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name }),
  });
  reloadServerList();
}

async function pullUser() {
  console.log('pull user');
  let res = await fetch('/pullChangedUsers', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    // body: JSON.stringify({ name }),
  });
}
//////////////////////////////////////////////////////////////////////////
function setCookie(cname, cvalue, exdays = 24) {
  var d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  var expires = 'expires=' + d.toUTCString();
  document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
}

function getCookie(cname) {
  var name = cname + '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return '';
}

function checkCookie() {
  var user = getCookie('username');
  if (user != '') {
    alert('Welcome again ' + user);
  } else {
    user = prompt('Please enter your name:', '');
    if (user != '' && user != null) {
      setCookie('username', user, 365);
    }
  }
}
